﻿using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace YDT.Projects.WebSite.Controllers
{
    public class HandlerA : DelegatingHandler
    {
        private readonly IMemoryCache memoryCache;// 本地缓存

        public HandlerA(IMemoryCache memoryCache)
        {
            this.memoryCache = memoryCache;
        }

        protected override Task<HttpResponseMessage> SendAsync(
         HttpRequestMessage request,
         CancellationToken cancellationToken
        )
        {
            Console.WriteLine("This is Handler A");

            HttpResponseMessage httpResponseMessage1 = memoryCache.Get<HttpResponseMessage>("tony");
            if (httpResponseMessage1 != null)
            {
                if (!httpResponseMessage1.Headers.CacheControl.NoCache && !httpResponseMessage1.Headers.CacheControl.NoStore)
                {
                    return Task.FromResult(httpResponseMessage1);
                }
                else
                {
                    var httpResponseMessage = base.SendAsync(request, cancellationToken).Result;
                    return Task.FromResult(httpResponseMessage);
                }
            } else
            {
                var httpResponseMessage = base.SendAsync(request, cancellationToken).Result;

                if (!httpResponseMessage.Headers.CacheControl.NoCache && !httpResponseMessage.Headers.CacheControl.NoStore)
                {
                    // 1.2 添加到缓存
                    MemoryCacheEntryOptions memoryCacheEntryOptions = new MemoryCacheEntryOptions();

                   /*var SS = httpResponseMessage.Headers.CacheControl.MaxAge;
                    SS.*/
                    // 1、过期时间(保证数据和源头一致)
                    memoryCacheEntryOptions.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1);

                    memoryCache.Set<HttpResponseMessage>("tony", httpResponseMessage, memoryCacheEntryOptions);
                }
                return Task.FromResult(httpResponseMessage);
            }
           
        }
    }
}
